<script setup lang="ts">
import type { FormInstance } from 'element-plus'
import { ElMessage } from 'element-plus'
import qs from 'qs'
import type { FormType } from './index'
import { GetDataDetail, PostCreateData, PutModifyData } from '@/api/modules/memberholiday'
import { GetAllData } from '@/api/modules/merchandiseControl'
import { GetTuangouTuanOption } from '@/api/modules/tuangou'
import { GetRenxuanOption } from '@/api/modules/renxuan'
import detailStore from '@/store/modules/NewCacheData'

const router = useRouter()
const route = useRoute()
const detailData = detailStore()

const ruleFormRef = ref<FormInstance>()
const ruleForm = ref<FormType>({
  name: '',
  banner: '',
  openType: 0,
  openDate: 0,
  productIdsSec: '',
  productIdsNom: '',
  tuanInfoIds: '',
  startDate: '',
  endDate: '',
  productNomPic: '',
  actModule: {
    act_type: 1,
    act_id: 0,
    banner: '',
    jump_url: '',
  },
})

const rules = reactive({
  sort: [
    { required: true, message: '请输入自定义排序', trigger: 'blur' },
  ],
})

// const openTypeArray = reactive([
//   { value: 1, label: '每月' },
//   { value: 2, label: '每周' },
// ])

// const productIdOptions = ref<any[]>([])
// const productIdsOptions = ref<any[]>([])
// const tuanInfoIdsOptions = ref<any[]>([])

const OptionObj = reactive({
  renxuanOption: [],
  productIdOptions: [],
  productIdsOptions: [],
  tuanInfoIdsOptions: [],
})

const id = route.query.id as string

// 图片上传赋值
function handleUploadSuccess(url: string, key: string) {
  if (key !== 'actModule') {
    ruleForm.value[key] = url
  }
  else {
    ruleForm.value.actModule.banner = url
  }
}

// 会员专享商品数组
const productIdsSecOptions = ref<any>([])

// 新增和删除的逻辑
// 添加新卡片
function addCard() {
  productIdsSecOptions.value.push({
    label: '',
    value: productIdsSecOptions.value.length + 1,
  })
}

// 删除卡片
function deleteCard(index: number) {
  const deletedValue = productIdsSecOptions.value[index].value
  productIdsSecOptions.value.splice(index, 1)

  // 调整被删除项后面的所有项的value
  productIdsSecOptions.value.forEach((item: any) => {
    if (item.value > deletedValue) {
      item.value--
    }
  })
}

// 调整顺序的方法
function handleSortChange(changedIndex: number) {
  const items = [...productIdsSecOptions.value]
  const changedItem = items[changedIndex]
  const newPosition = changedItem.value // 用户输入的新位置 (1-based)
  const oldPosition = items.findIndex(item => item.value === changedItem.value) + 1 // 当前实际位置

  // 验证输入
  if (newPosition < 1 || newPosition > items.length) {
    changedItem.value = oldPosition
    return
  }

  // 临时移除被移动的元素
  const [movedItem] = items.splice(changedIndex, 1)

  // 插入到新位置 (注意数组是0-based)
  items.splice(newPosition - 1, 0, movedItem)

  // 重新计算所有元素的value (1-based连续值)
  items.forEach((item, index) => {
    item.value = index + 1
  })

  // 更新原数组
  productIdsSecOptions.value = items
}

// 提交
async function SubmitData() {
  const params = {
    ...ruleForm.value,
  }
  params.productIdsSec = (ruleForm.value.productIdsSec as string[]).join(',')
  ruleForm.value.productIdsNom = productIdsSecOptions.value.map((item: any) => item.label)
  params.productIdsNom = (ruleForm.value.productIdsNom as string[]).join(',')
  params.openDate = 0
  params.actModule = JSON.stringify(params.actModule)
  // console.log(params)
  // return 0

  if (id) {
    // 编辑
    params.id = id
    PutModifyData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('编辑成功')
        router.push({ name: 'memberholidayIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`编辑失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`编辑失败。${errorStr}`)
        }
      }
    })
  }
  else {
    // 添加
    PostCreateData(params).then((res: any) => {
      if (res.statusCode === 200) {
        ElMessage.success('添加成功')
        detailData.emptyFormData('memberholidayFrom')
        router.push({ name: 'memberholidayIndex' })
      }
      else {
        if (typeof res.errors === 'string') {
          ElMessage.error(`添加失败。${res.errors}`)
        }
        else {
          let errorStr = ''
          for (const key in res.errors) {
            errorStr += `${key}：${res.errors[key]}；`
          }
          ElMessage.error(`添加失败。${errorStr}`)
        }
      }
    })
  }
}

onMounted(async () => {
  const params = qs.stringify({ ProductName: '', IsActive: true })
  await GetAllData(params).then((res: any) => {
    OptionObj.productIdsOptions = res.data
  })
  const param = qs.stringify({ ProductName: '', IsActive: true, FlagList: [3] })
  await GetAllData(param).then((res: any) => {
    OptionObj.productIdOptions = res.data
  })
  await GetRenxuanOption().then((res: any) => {
    OptionObj.renxuanOption = res.data
  })
  const TuangouParams = {
    PageIndex: 1,
    PageSize: 10000,
  }
  await GetTuangouTuanOption(TuangouParams).then((res: any) => {
    OptionObj.tuanInfoIdsOptions = res.data0
  })
  if (id) {
    await GetDataDetail(id).then((res: any) => {
      if (res.statusCode === 200) {
        ruleForm.value = res.data
        ruleForm.value.productIdsSec = res.data.productIdsSec.split(',')
        ruleForm.value.productIdsNom = res.data.productIdsNom.split(',')
        if (res.data.actModule !== '') {
          ruleForm.value.actModule = JSON.parse(res.data.actModule)
        }
        else {
          ruleForm.value.actModule = {
            act_type: 1,
            act_id: 0,
            banner: '',
            jump_url: '',
          }
        }
      }
    })
  }
  else {
    ruleForm.value = detailData.getFormData('memberholidayFrom')
  }

  watch(ruleForm, (newValue) => {
    if (!id) {
      detailData.rememberFormData('memberholidayFrom', newValue)
    }
  }, { deep: true })

  productIdsSecOptions.value = (ruleForm.value.productIdsNom as string[]).map((item, index) => ({
    label: item,
    value: index + 1,
  }))
})
</script>

<template>
  <div>
    <PageHeader :title="id ? '编辑' : '添加'" />
    <ElForm ref="ruleFormRef" label-position="top" label-width="80px" :rules="rules" :model="ruleForm">
      <PageMain title="基础信息">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="活动标题">
              <el-input v-model="ruleForm.name" style="width: 300px;" maxlength="6" placeholder="请输入活动标题" />
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="8">
            <ElFormItem label="日期类型">
              <el-radio-group v-model="ruleForm.openType">
                <el-radio v-for="item in openTypeArray" :key="item.value" :value="item.value">
                  {{ item.label }}
                </el-radio>
              </el-radio-group>
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="开始日期" prop="openDate">
              <el-date-picker
                v-model="ruleForm.startDate"
                type="datetime"
                placeholder="请选择日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="结束日期" prop="openDate">
              <el-date-picker
                v-model="ruleForm.endDate"
                type="datetime"
                placeholder="请选择日期"
                value-format="YYYY-MM-DD HH:mm:ss"
              />
            </ElFormItem>
          </ElCol>
          <!-- <ElCol :md="24">
            <ElFormItem label="日期(每月几号或每周几)" prop="openDate">
              <el-input v-model="ruleForm.openDate" style="width: 300px;" placeholder="请输入自定义排序" />
            </ElFormItem>
          </ElCol> -->
          <ElCol :md="8">
            <ElFormItem label="顶部banner">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.banner" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'banner')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="16">
            <ElFormItem label="商品标题图片">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.productNomPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'productNomPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="弹窗图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.layerPic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'layerPic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="分享图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.sharePic" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'sharePic')"
              />
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="分享语">
              <el-input v-model="ruleForm.shareTxt" placeholder="请输入活动标题" style="max-width: 500px;" type="textarea" />
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.openType !== 3" :md="8">
            <ElFormItem label="团购活动">
              <el-select v-model="ruleForm.tuanInfoIds" placeholder="请选择团购活动" filterable multiple>
                <el-option
                  v-for="item in (OptionObj.tuanInfoIdsOptions as any)"
                  :key="item.tuanInfoId"
                  :label="`${item.tuanInfoId}--${item.tuanTitle}`"
                  :value="`${item.tuanInfoId}`"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol v-if="ruleForm.openType !== 3" :md="8">
            <ElFormItem label="秒杀商品">
              <el-select
                v-model="ruleForm.productIdsSec"
                placeholder="请选择秒杀商品"
                filterable multiple
              >
                <el-option
                  v-for="item in (OptionObj.productIdOptions as any)"
                  :key="item.productId"
                  :label="`${item.productId}--${item.productName}`"
                  :value="`${item.productId}`"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="24">
            <ElFormItem label="会员专享商品">
              <!-- <el-select v-model="ruleForm.productIdsNom" multiple placeholder="请选择会员专享商品" filterable style="max-width: 95%;">
                <el-option
                  v-for="item in productIdsOptions"
                  :key="item.productId"
                  :label="`${item.productId}--${item.productName}`"
                  :value="`${item.productId}`"
                />
              </el-select> -->
              <ElRow :gutter="20">
                <ElCol v-for="(item, index) in productIdsSecOptions" :key="item" :md="6">
                  <el-card style="margin-bottom: 10px;">
                    <!-- {{ item }} -->
                    <el-select v-model="item.label" placeholder="请选择会员专享商品" filterable style="max-width: 95%;">
                      <el-option
                        v-for="items in (OptionObj.productIdsOptions as any)"
                        :key="items.productId"
                        :label="`${items.productId}--${items.productName}`"
                        :value="`${items.productId}`"
                      />
                    </el-select>
                    <div style="display: flex; margin-top: 10px;">
                      排序： <el-input
                        v-model.number="item.value"
                        placeholder="请输入自定义排序"
                        style="width: 80%;"
                        @blur="handleSortChange(index)"
                      />
                    </div>
                    <template #footer>
                      <div class="text-right">
                        <el-button v-if="productIdsSecOptions.length === item.value" type="success" size="small" @click="addCard">
                          添加
                        </el-button>
                        <el-button type="danger" size="small" @click="deleteCard(index)">
                          删除
                        </el-button>
                      </div>
                    </template>
                  </el-card>
                </ElCol>
              </ElRow>
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
      <PageMain v-if="id === '507'" title="援疆会员关联活动">
        <ElRow :gutter="20">
          <ElCol :md="8">
            <ElFormItem label="活动类型">
              <el-select v-model="ruleForm.actModule.act_type" placeholder="请选择会员专享商品" filterable>
                <el-option label="任选活动" :value="1" />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="活动ID">
              <el-select v-model="ruleForm.actModule.act_id" placeholder="请选择会员专享商品" filterable>
                <el-option
                  v-for="items in (OptionObj.renxuanOption as any)"
                  :key="items.rxActId"
                  :label="`${items.rxActId} --${items.title}`"
                  :value="`${items.rxActId}`"
                />
              </el-select>
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="跳转链接">
              <el-input v-model="ruleForm.actModule.jump_url" placeholder="请输入跳转链接" />
            </ElFormItem>
          </ElCol>
          <ElCol :md="8">
            <ElFormItem label="banner图">
              <ImageUpload
                width="auto" height="200" :size="5" :url="ruleForm.actModule.banner" :ext="['jpg', 'png']"
                @on-success="(imgUrl: string) => handleUploadSuccess(imgUrl, 'actModule')"
              />
            </ElFormItem>
          </ElCol>
        </ElRow>
      </PageMain>
    </ElForm>
    <div style="height: 80px;" />
    <FixedActionBar>
      <ElButton type="primary" size="large" @click="SubmitData()">
        提交
      </ElButton>
    </FixedActionBar>
  </div>
</template>

<style lang="scss" scoped>
.box {
  .title {
    display: flex;
    justify-content: space-between;
    margin-bottom: 10px;
  }
}

.card-box {
  display: grid;
  grid-template-columns: 1fr 1fr;
  grid-gap: 10px;
}
</style>
